package com.nio;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilelockDemo {
    public static void main(String[] args) throws Exception {
        String input = "java";
        ByteBuffer wrap = ByteBuffer.wrap(input.getBytes());
        String filePath = "F:\\1.txt";
        Path path = Paths.get(filePath);
        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
        fileChannel.position(fileChannel.size()-1);

        FileLock lock = fileChannel.tryLock(0, Long.MAX_VALUE, false);
        System.out.println("设置共享锁"+lock.isShared());

        fileChannel.write(wrap);
        fileChannel.close();
        System.out.println("写操作完成");
        // 开始读数据
        readFile(filePath);
    }

    private static void readFile(String filePath) throws Exception {
        FileReader reader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String readLine = bufferedReader.readLine();
        System.out.println("读取内容");
        while (readLine != null){
            System.out.println("readLine---->"+readLine);
        }
        reader.close();
        bufferedReader.close();
    }
}
